package com.liu.netty.server;

import com.liu.common.utils.JacksonUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.nio.channels.SocketChannel;
import java.util.Map;

@Slf4j
public class CollectHandler extends SimpleChannelInboundHandler<String> {

//###<TaskID=06750;TaskFlag=1;TaskContent{ObjectAddress=sx0020;CommandStyle=1;DataID=2;DataContent<>}>###
//    回复报文:###<TaskID=06750;TaskContent{ResultFlg=0;Content<DateTime=2019-08-28 14:45:19>}>###19>}>###

    @Override
    protected void messageReceived(ChannelHandlerContext ctx, String msg) throws Exception {
//       接收到的消息
        System.out.println(msg);
        System.out.println("接收到的长度"+msg.length());
        Map map =JacksonUtil.readValue(msg, Map.class);
//        log.info("map:{}" ,map);
        String chanelId =ctx.channel().id().asLongText();
        String clientId =map.get("id").toString();
        String image =map.get("image").toString();
//         log.info("图片为：{}",image);
        System.out.println(JacksonUtil.toJSon(map));
        ClientsMap.addClient(clientId,chanelId);


//        返回数据
        ctx.writeAndFlush("给你回话"+System.getProperty("line.separator"));
    }


    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        super.handlerAdded(ctx);
        System.out.println("新的用户连接进来");
        ClientsMap.addChannel(ctx.channel().id().asLongText(),ctx);
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        super.handlerRemoved(ctx);

        for(String s :ClientsMap.getClientKeys()) {
            if(ClientsMap.getChannelId(s).equals(ctx.channel().id().asLongText())){
                ClientsMap.removeClient(s);
            }
        }
        ClientsMap.removeChannel(ctx.channel().id().asLongText());
        System.out.println("一个用户退出了请求");
    }
}
